<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission('0',1)">添加权限</el-button>
        </div>

        <el-table :data="permissionList" border row-key="id">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type===1" type="text" @click="addPermission(scope.row.id,2)">添加</el-button>
              <el-button type="text" @click="editPermission(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delPermission(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 添加编辑权限点弹框 -->
        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog :title="isEdit?'编辑权限点':'新增权限点'" :visible="showDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <!-- 底部按钮 -->
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="addOrEdit">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, getPermissionDetail, updatePermission, delPermission } from '@/api/permission'
import { transTree } from '@/utils'
export default {
  name: 'Permission',
  data() {
    // 自定义校验code
    const checkCode = (rule, value, callback) => {
      let codeList = this.originList.map(item => item.code)
      if (this.isEdit) {
        codeList = this.originList.filter(item => item.id !== this.formData.id).map(item => item.code)
      }
      codeList.includes(value) ? callback(new Error(value + '已存在')) : callback()
    }

    // 自定义校验name
    const checkName = (rule, value, callback) => {
      // 找到同级的
      let nameList = this.originList.filter(item => item.pid === this.formData.pid).map(item => item.name)
      if (this.isEdit) {
        nameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id).map(item => item.name)
      }
      nameList.includes(value) ? callback(new Error(value + '已存在')) : callback()
    }
    return {
      permissionList: [],
      showDialog: false,
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: checkCode, trigger: 'blur' }
        ]
      },
      isEdit: false,
      // editId: '',
      originList: []
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 点击删除按钮
    async delPermission(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes === 'cancel') return
      const res = await delPermission(id)
      // console.log(res)
      // 提示
      this.$message.success(res.message)
      // 刷新页面
      this.getPermissionList()
    },

    // 点击编辑按钮
    async editPermission(id) {
      // this.editId = id
      // 获取数据进行回填
      const res = await getPermissionDetail(id)
      // console.log(res)
      this.formData = res.data
      // 切换为编辑状态
      this.isEdit = true
      // 打开弹框
      this.showDialog = true
    },

    // 编辑权限点
    async editPermissionSubmit() {
      const res = await updatePermission(this.formData)
      // console.log(res)
      // 提示
      this.$message.success(res.message)
      // 关闭弹框
      this.showDialog = false
      // 刷新页面
      this.getPermissionList()
    },

    // 添加权限点
    async addPermissionSubmit() {
      const res = await addPermission(this.formData)
      // console.log(res)
      // 提示
      this.$message.success(res.message)
      // 关闭弹框
      this.showDialog = false
      // 刷新页面
      this.getPermissionList()
    },

    // 点击确定按钮
    addOrEdit() {
      // 兜底校验
      this.$refs.perForm.validate(async valid => {
        if (!valid) return
        this.isEdit ? this.editPermissionSubmit() : this.addPermissionSubmit()
      })
    },

    // 点击添加按钮
    addPermission(pid, type) {
      // console.log(pid, type)
      this.formData.pid = pid
      this.formData.type = type
      // 切换为添加状态
      this.isEdit = false
      this.showDialog = true
    },

    // 点击取消
    btnCancel() {
      // 清空重置数据
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      // 重置表单
      this.$refs.perForm.resetFields()
      // 关闭弹框
      this.showDialog = false
    },

    // 获取权限点
    async getPermissionList() {
      const res = await getPermissionList()
      // console.log(res)
      this.originList = res.data.map(item => ({
        id: item.id,
        pid: item.pid,
        name: item.name.trim(),
        code: item.code
      }))
      // console.log(this.originList)
      this.permissionList = transTree(res.data, '0')
    }
  }
}
</script>

<style lang="scss" scoped></style>
